import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;

//服务端可以接受多个客户端
//能向多个客户端发送命令
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(61234);
        CopyOnWriteArrayList<Socket>  sockets = new CopyOnWriteArrayList<>();
        //1、能够接受多个客户端
        new Thread(){
            @Override
            public void run() {
                try {
                    while(true) {
                        Socket socket = serverSocket.accept();
                        sockets.add(socket);

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //2、能够给所有的客户端发送数据
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入命令内容");
           String cmd = scanner.nextLine();

            sendToAll(sockets,cmd);
        }


    }

    private static void sendToAll(CopyOnWriteArrayList<Socket> sockets, String cmd) {
        for(Socket socket:sockets){

            try {
               DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
               dataOutputStream.writeUTF(cmd);
               dataOutputStream.flush();
            } catch (IOException e) {
                //e.printStackTrace();
                sockets.remove(socket);
            }

        }
    }
}
